package com.majx.controller.interceptor;


import com.majx.util.TokenUtil;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token拦截器
 */
public class TokenInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        System.out.println("------------- url="+url);
        System.out.println("请求方式 = "+request.getMethod());
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }

        if (!url.endsWith("user/login")) {
            String Authorization = request.getHeader("Authorization");
            String[] split = Authorization.split("\\s");
            String token = split[1];
            System.out.println("token="+token);

            System.out.println("校验合法性");

            boolean flag = TokenUtil.verify(token);

            System.out.println("flag = "+flag);

            if(flag){
                System.out.println("合法");
                return true;
            } else {
                System.out.println("非法");
                response.sendError(response.SC_UNAUTHORIZED);
                return false;
            }
        }
        System.out.println("合法");
        return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
